﻿using System;
using Eneta.Portal.Common.Dto;
using Microsoft.SharePoint;

namespace Eneta.Portal.Common.Repository
{
    /// <summary>
    /// Repository for custom HTML blocks.
    /// </summary>
    public class HtmlRepository : BaseRepository
    {
        public HtmlRepository(SPWeb web): base(web){}

        /// <summary>
        /// Gets the HTML by unique identificator.
        /// </summary>
        /// <param name="identificator">The unique identificator.</param>
        public HtmlDto GetHtmlBy(string identificator)
        {
            HtmlDto dto = null;
            var sec = new SPSecurity.CodeToRunElevated(delegate
            {
                using (var site = new SPSite(SiteId))
                using (var web = site.OpenWeb())
                {
                    dto = GetHtmlBy(web, identificator);
                }
            });
            SPSecurity.RunWithElevatedPrivileges(sec);

            return dto;
        }

        private HtmlDto GetHtmlBy(SPWeb web, string identificator)
        {
            var list = web.Lists["HtmlControls"];

            var queryString = "<Where><Eq><FieldRef Name='Identificator' /><Value Type='Text'>{0}</Value></Eq></Where>";
            queryString = string.Format(queryString, identificator);

            var items = ExecuteQuery(list, queryString);
            Logger.LogInfo("HtmlRepository: Query end: " + queryString, GetType().ToString());
            if (items == null)
            {
                Logger.LogInfo("HtmlRepository: Item was null: " + list.Title, GetType().ToString());
                return null;
            }
            if (items.Count == 0)
            {
                Logger.LogInfo("HtmlRepository: Items count was null: " + list.Title, GetType().ToString());
                return null;
            }
            var html = CreateHtml(items[0]);
            return html;
        }

        public DateTime GetLastChangeDate()
        {
            var modified = DateTime.MinValue;

            var sec = new SPSecurity.CodeToRunElevated(delegate
                {
                    using (var site = new SPSite(SiteId))
                    using (var web = site.OpenWeb())
                    {
                        var list = web.Lists["HtmlControls"];
                        var queryString = "<OrderBy><FieldRef Name='Modified' Ascending='False' /></OrderBy>";
                        var query = new SPQuery { Query = queryString, RowLimit = 1 };
                        query.ViewFields = "<FieldRef Name='Modified' />";
                        var items = list.GetItems(query);

                        if (items == null)
                            return;
                        if (items.Count == 0)
                            return;

                        modified = (DateTime)items[0]["Modified"];
                    }
                });
            SPSecurity.RunWithElevatedPrivileges(sec);

            return modified;
        }

        private HtmlDto CreateHtml(SPListItem item)
        {
            var dto = new HtmlDto
            {
                Identification = item["Identificator"].ToString(),
                Html = item["Html"].ToString(),
            };
            return dto;
        }
    }
}
